package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.common.MyTouch;
import com.loveto.constant.LovetoConstant;
import com.loveto.model.TournamentInfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class JoinedTournamentListActivity extends BaseActivity implements
View.OnClickListener, View.OnTouchListener {

	// 사용하는 변수들
	private LinearLayout contentMain; // 전체 레이아웃 // LinearLayout
	private ImageView ingTournamentImageView;
	private ImageView completeTournamentImageView;
	Animation shake;
	private String memberid = "";
	private ProgressDialog progressDialog;
	private Handler myHandler = new Handler();
	private int newMessageCnt = 0;
	private int not_select_winner_tournamentID = 0;
	private int not_view_winner_tournamentID = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_joined_tournament_list);
		
		// 터치 리스너 달기 // 버튼
		RelativeLayout footer01 = (RelativeLayout) findViewById(R.id.btn_footer01);
		footer01.setOnTouchListener(this);
		RelativeLayout footer03 = (RelativeLayout) findViewById(R.id.btn_footer03);
		footer03.setOnTouchListener(this);
		RelativeLayout footer04 = (RelativeLayout) findViewById(R.id.btn_footer04);
		footer04.setOnTouchListener(this);
		RelativeLayout footer05 = (RelativeLayout) findViewById(R.id.btn_footer05);
		footer05.setOnTouchListener(this);
		
		contentMain = (LinearLayout) findViewById(R.id.content_main);
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = pref.getString("memberid", "");
		progressDialog = new ProgressDialog(this);
		ingTournamentImageView = (ImageView)findViewById(R.id.ing_tournament_btn);
		completeTournamentImageView = (ImageView)findViewById(R.id.complete_tournament_btn);
		ingTournamentImageView.setOnClickListener(this);
		completeTournamentImageView.setOnClickListener(this);
		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		
		if(isNetworkAvailableAndNotice()) {
			getJoiningTournamentList("N");
			getNewMessage();
		}
	}
	
	@Override
	public void onClick(View v) {
		Intent intent = null;
		RelativeLayout vParent;
		TextView eventClassNameTextView;
		String eventClassName;
		TextView v_userID;
		String userID;
		
		switch(v.getId()) {
		case R.id.ing_tournament_btn :
			ingTournamentImageView.setImageResource(R.drawable.btn_joined_progress_selected);
			completeTournamentImageView.setImageResource(R.drawable.btn_joined_finished_unselected);
			v.startAnimation(shake);
			getJoiningTournamentList("N");
			break;
		case R.id.complete_tournament_btn :
			ingTournamentImageView.setImageResource(R.drawable.btn_joined_progress_unselected);
			completeTournamentImageView.setImageResource(R.drawable.btn_joined_finished_selected);
			v.startAnimation(shake);
			getJoiningTournamentList("Y");
			break;
		case R.id.tourlist_photo :
			vParent = (RelativeLayout)v.getParent();
			v_userID = (TextView)vParent.findViewById(R.id.userID);
			userID = (String)v_userID.getText();
			intent = new Intent(JoinedTournamentListActivity.this, UserinfoViewOthersActivity.class);
			intent.putExtra("memberid_other", userID);
			startActivity(intent);
			break;
		case R.id.tourinfo_arrow :
		case R.id.tourinfo_talkbox :
			vParent = (RelativeLayout)v.getParent();
			eventClassNameTextView = (TextView)vParent.findViewById(R.id.event_class_name);
			eventClassName = (String)eventClassNameTextView.getText();
			intent = new Intent(JoinedTournamentListActivity.this, getClassForStringName(eventClassName));
			TextView text_id = (TextView)vParent.findViewById(R.id.tournamentID);
			String tournemant_id = (String)text_id.getText();
			intent.putExtra("tournamentID", tournemant_id);
			intent.putExtra("roundSeq", 1);
			startActivity(intent);
			break;
		}
	}

	private Class getClassForStringName(String eventClassName) {
		Class result;
		if ("InfoTournamentActivity".equals(eventClassName)) {
			result = InfoTournamentActivity.class;
		} else if ("SelectWinnerIntermidRoundActivity".equals(eventClassName)) {
			result = SelectWinnerIntermidRoundActivity.class;
		} else if ("SlideshowWinnerIntermidRoundActivity".equals(eventClassName)) {
			result = SlideshowWinnerIntermidRoundActivity.class;
		} else {
			result = InfoTournamentActivity.class;
		}
		return result;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_footer01:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(LovotoMainActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer02:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(JoinedTournamentListActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer03:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(MessageMainActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer04:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(UserinfoViewMineActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer05:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(SetupMainActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		}
		return true;
	}

	//화면 전환 시켜주기
		private void gotoActive(Class<?> targetClass, View v, int d) {
			SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
			String memberid = pref.getString("memberid", "");
			Log.d("tag", "memberid : " + memberid);
			
			if(!"LoginMainActivity".equals(targetClass.getName()) && memberid.length() == 0 ) {
				Intent intent = new Intent(JoinedTournamentListActivity.this, LoginMainActivity.class);
				startActivity(intent);
			} else {
				Intent intent;
				intent = new Intent(JoinedTournamentListActivity.this, targetClass);
				startActivity(intent);
				v.setBackgroundResource(d);	
			}
		}
	
	private void getJoiningTournamentList(final String iscompleted) {
		progressDialog.setMessage("정보를 불러오고있습니다.");
		progressDialog.show();
		
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				
							try {
								//UI 를 건들기 때문에 핸들러 사용.
								myHandler.post(new Runnable() {
									@Override
									public void run() {
										contentMain.removeAllViews();
									}
								});
								
								Log.d("tag", "setRoundInfo() start");
								StringBuffer url = new StringBuffer(LovetoConstant.JOINED_TOURNAMENT_URL);
								url.append("?memberid=").append(memberid).append("&resultConfirmStatus=").append(iscompleted);
								String jsonText = JsonUtils.getStringFromUrl(url.toString());
								Log.d("tag", "jsonText : " + jsonText);
								JSONArray jsonArray = new JSONArray(jsonText);
								int jsonArrayLen = jsonArray.length();
								final List<RelativeLayout> tournamentInfoLayoutList = new ArrayList<RelativeLayout>(); // 하나의 row Layout 들을 간직한 List
								final List<String> photoUrlList = new ArrayList<String>(jsonArrayLen);  // 사진url array
								
								for (int i = 0; i < jsonArrayLen; i++) {
									JSONObject object = jsonArray.getJSONObject(i);
									String gender = object.getString("gender");
									String timediff = object.getString("timediff");
									String winnerMemberid = object.getString("winner_memberid");
									String tournamentMakerMemberid = object.getString("tournament_maker_memberid");
									int tournamentStatus = object.getInt("tournament_status");
									
									Log.d("tag", "gender : " + gender);
									Log.d("tag", "timediff : " + timediff);
									Log.d("tag", "winnerMemberid : " + winnerMemberid);
									Log.d("tag", "tournamentStatus : " + tournamentStatus);
									
									if (timediff == null || (timediff != null && timediff.equals("null"))) {
										timediff = "";
									}
															
									String winYN = "N";
									
									if (winnerMemberid != null && winnerMemberid == memberid) {
										winYN = "Y";
									}
									
									String statusMessage = "";
									String eventClass = "InfoTournamentActivity";
									
									if ("Y".equals(iscompleted)) { //완료된 LOVEto
										gender = "completeStyle";
										int lastSuccessRound = object.getInt("last_success_round");
										
										// 본인이 만든 토너먼트이면(주최자 입장일 때)
										if (tournamentMakerMemberid != null && tournamentMakerMemberid.equals(memberid)) {
											if (tournamentStatus == 2){
												statusMessage = "주최자" + tournamentMakerMemberid + "님의 3일간 미접속으로 취소";
											} else if (winnerMemberid != null) {
												statusMessage = winnerMemberid + "님 토너먼트 최종 우승!";
											} else {
												Log.d("tag", "something wrong!");
											}
										} else { // 참여자 입장일 때 
											if (tournamentStatus == 2) {
												statusMessage = "주최자의 3일간 미접속으로 취소"; // 진행 취소 (주최자의 결과 선택 3일 지연 시)
											} else if (winYN == "Y") { // 우승 성공
												statusMessage = "토너먼트 최종 우승!";
											} else  if (winYN == "N" && lastSuccessRound == 0) { // 1 ROUND 통과 실패
												statusMessage = "1Round 통과 실패";
											} else  if (winYN == "N" && lastSuccessRound > 0) { // 1 ROUND 통과 성공 + 우승 실패 (진출 한 마지막 라운드로 표시 해줌)
												statusMessage = lastSuccessRound + "Round 통과 성공 + 우승 실패";
											} else {
												Log.d("tag", "something wrong!");
											}
										}
									} else if ("N".equals(iscompleted)) { //참여중 LOVEto
										
										// 본인이 만든 토너먼트이면(주최자)
										if (tournamentMakerMemberid != null && tournamentMakerMemberid.equals(memberid)) {
											if (tournamentStatus == 1 && timediff.indexOf('-') == -1){ //참여 마감 전
												statusMessage = "참여완료" + timediff + "남음";
												eventClass = "InfoTournamentActivity";
											} else if (tournamentStatus == 1 && timediff.indexOf('-') != -1 &&(winnerMemberid == null  || (winnerMemberid != null && winnerMemberid.equals("null")))) { //마감 후 + 우승자 결정 전
												statusMessage = "참여 마감! 터치해서 우승자를 결정하세요!";
												eventClass = "SelectWinnerIntermidRoundActivity";
											} else if (tournamentStatus == 1 && winnerMemberid != null) { //우승자 결정 후 + 우승자가 결과 확인 전
												statusMessage = "우승자 결과 확인 대기중...";
												eventClass = "SlideshowWinnerIntermidRoundActivity";
											} else {
												Log.e("tag", "something wrong!");
											}
										} else { // 참여자 입장일 때
											if (tournamentStatus == 1 && timediff.indexOf('-') == -1){ //참여 마감 전
												statusMessage = "참여완료" + timediff + "남음";
												eventClass = "InfoTournamentActivity";
											} else if (tournamentStatus == 1 && timediff.indexOf('-') != -1) { //마감 후 + 우승자 결정 전
												statusMessage = "우승자 결정 대기중..";
												eventClass = "InfoTournamentActivity";
											} else if (tournamentStatus == 0) { //우승자 결정 후 + 결과 확인 전
												statusMessage = "우승자 결정! 터치해서 결과를 확인하세요!";
												eventClass = "SlideshowWinnerIntermidRoundActivity";
											} else {
												Log.e("tag", "something wrong!");
											}
										}
									}
									
									TournamentInfo tournamentInfo = new TournamentInfo(
											object.getInt("tournamentid"),
											object.getString("tournament_title"),
											object.getInt("participant_cnt"),
											object.getString("tournament_maker_memberid"),
											statusMessage, object.getString("regdate"),
											object.getString("local"),
											object.getString("local_detail"),
											object.getString("age"), gender);

									// 하나의 row 만들기
									final RelativeLayout tournamentInfoLayout = makeRelativeLayout(tournamentInfo, photoUrlList, eventClass);
									
									//UI 를 건들기 때문에 핸들러 사용.
									myHandler.post(new Runnable() {
										@Override
										public void run() {
											contentMain.addView(tournamentInfoLayout);
										}
									});
									
									// 기능 : 메인 layout 에 add // 콜백함수 : onProgressUpdate
									
									// 사진 전체 다운로드를 위하여
									tournamentInfoLayoutList.add(tournamentInfoLayout);
								}
								
								//UI 를 건들기 때문에 핸들러 사용.
								myHandler.post(new Runnable() {
									@Override
									public void run() {
										// 사진 한꺼번에 다운로드
										ImageDownloader imageDownloader = new ImageDownloader();
										int photoUrlArraySize = photoUrlList.size();
										for (int i = 0; i < photoUrlArraySize; i++) {
											String photoUrl = photoUrlList.get(i);
											ImageView imgView = (ImageView)tournamentInfoLayoutList.get(i).findViewById(R.id.tourlist_photo);
											imageDownloader.download(photoUrl, imgView);
										}
										
										// 아무것도 없을 경우
										if(photoUrlArraySize == 0) {
											viewToast(Gravity.CENTER, 0, 0, "데이터가 없습니다.");
										}
									}
								});
							} catch (JSONException e) {
								e.printStackTrace();
								viewToast(Gravity.CENTER, 0, 0, "데이타를 받아오는 중 오류가 발생하였습니다");
								Log.d("tag", "getJoiningTournamentList() error, " + e.getMessage());
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
								viewToast(Gravity.CENTER, 0, 0, "데이터가 없습니다.");
								Log.d("tag", "getJoiningTournamentList() error, " + e.getMessage());
							} finally {
								progressDialog.dismiss();
								Log.d("tag", "getJoiningTournamentList() end");
							}
				
			}
		};
		new Thread(runnable).start();
	}
	
	
	// 하나의 row를 만들기
	private RelativeLayout makeRelativeLayout(TournamentInfo tournamentInfo, List<String> photoUrlList, String eventClass) {
		RelativeLayout tournamentListInfo = null;
		if ("M".equals(tournamentInfo.getGender())) {
			tournamentListInfo = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_joined_man_style, null);
		} else if ("F".equals(tournamentInfo.getGender())){
			tournamentListInfo = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_joined_woman_style, null);
		} else if ("completeStyle".equals(tournamentInfo.getGender())) {
			tournamentListInfo = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_joined_complete_style, null);
		}

		// 유저 인포 텍스트 변경
		TextView userInfo = (TextView)tournamentListInfo.findViewById(R.id.tourlist_userinfo_text);
		StringBuffer sb = new StringBuffer();
		sb.append(tournamentInfo.getTournamentMakerMemberid());
		sb.append(", ");
		sb.append(tournamentInfo.getLocal());
		if (tournamentInfo.getLocal_detail() != null) {
			if ( (!tournamentInfo.getLocal_detail().equals("")) && (!tournamentInfo.getLocal_detail().equals("null"))) {
				sb.append(" ");
				sb.append(tournamentInfo.getLocal_detail());
			}
		}
		sb.append(", ");
		sb.append(tournamentInfo.getAge());
		userInfo.setText(sb);

		// 토너먼트 ID 달아주기
		TextView tourID = (TextView)tournamentListInfo.findViewById(R.id.tournamentID);
		tourID.setText("" + tournamentInfo.getTournamentid());
		
		// 유저ID 달아주기
		TextView userID = (TextView)tournamentListInfo.findViewById(R.id.userID);
		userID.setText(tournamentInfo.getTournamentMakerMemberid());
		
		// 이동할 대상 class 명 달아주기
		TextView eventClassName = (TextView)tournamentListInfo.findViewById(R.id.event_class_name);
		eventClassName.setText(eventClass);

		// 토너먼트 제목 변경
		TextView tourTitle = (TextView)tournamentListInfo.findViewById(R.id.tourinfo_title_text);
		tourTitle.setText(tournamentInfo.getTournamentTitle());

		// 참여자 수
		TextView participantCnt = (TextView)tournamentListInfo.findViewById(R.id.tourinfo_participant_cnt);
		// StringBuffer 초기화
		sb.setLength(0);
		// 재사용
		sb.append("[");
		sb.append(tournamentInfo.getParticipantCnt());
		sb.append("]");
		participantCnt.setText(sb);

		// 마감 시간
		TextView deadlineText = (TextView)tournamentListInfo.findViewById(R.id.tourinfo_deadline_text);
		deadlineText.setText(tournamentInfo.getAnswerEndtime());

		// 사진 셋팅
		// StringBuffer 초기화
		sb.setLength(0);
		// 재사용
		sb.append(LovetoConstant.PHOTO_THUMB_URL);
		sb.append(tournamentInfo.getTournamentMakerMemberid());
		sb.append(".jpg");
		photoUrlList.add(sb.toString());

		//클릭 리스너 달기
		ImageView userphoto = (ImageView)tournamentListInfo.findViewById(R.id.tourlist_photo);
		userphoto.setOnClickListener(this); //사진
		userInfo.setOnClickListener(this); //유저정보텍스트
		RelativeLayout tournamentTitle = (RelativeLayout)tournamentListInfo.findViewById(R.id.tourinfo_talkbox);
		tournamentTitle.setOnClickListener(this); //말풍선
		ImageView userarrow = (ImageView)tournamentListInfo.findViewById(R.id.tourinfo_arrow);
		userarrow.setOnClickListener(this);

		return tournamentListInfo;
	}
	
	
	private void getNewMessage() {
		
		//비로그인 시 실행하지 않음.
		if ("".equals(memberid)) {
			return;
		}
		
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				
				try {
					
					StringBuffer URL = new StringBuffer();
					URL.append(LovetoConstant.MESSAGE_CHECK_NEW_URL);
					URL.append("?memberid=").append(memberid);
					Log.d("tag", "URL: " + URL.toString());
					//서버에서 정보 받아오기
					String jsonText = JsonUtils.getStringFromUrl(URL.toString());
					Log.d("tag", "jsonText: " + jsonText);
					JSONObject getObject = new JSONObject(jsonText);
					newMessageCnt = getObject.getInt("new_cnt");
					Log.d("tag", "newMessageCnt: " + newMessageCnt);
					not_select_winner_tournamentID = getObject.getInt("not_select_winner_tournamentID");
					Log.d("tag", "not_select_winner_tournamentID: " + not_select_winner_tournamentID);
					not_view_winner_tournamentID = getObject.getInt("not_view_winner_tournamentID");
					Log.d("tag", "not_view_winner_tournamentID: " + not_view_winner_tournamentID);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					Log.d("tag", "Get Json error : " + e.toString());
				} catch (JSONException e) {
					e.printStackTrace();
					Log.d("tag", "Get Json error : " + e.toString());
				} finally {
					// 풋터에 새 쪽지 개수 보여주기
					myHandler.post(new Runnable() {
						@Override
						public void run() {
							//풋터에 새로 받은 쪽지 개수 표시하기
							TextView vNewMsg = (TextView) findViewById(R.id.message_new_cnt);
							if (newMessageCnt !=0) {
								vNewMsg.setText("" + newMessageCnt);
								vNewMsg.setVisibility(TextView.VISIBLE);
							}
							if (not_select_winner_tournamentID != 0 || not_view_winner_tournamentID != 0) {
								showSimpleAlertForSelectOrViewWinner();
							}
						}
					});
				}
				Log.d("tag", "sendTalkMessage() end");
			}
		};
		new Thread(runnable).start();
	}

	private void showSimpleAlertForSelectOrViewWinner() {
		String title;
		String msg;
		if (not_select_winner_tournamentID != 0) {
			title = "토너먼트 주최완료!";
			msg = "주최 한 토너먼트의 마감시간이 완료되어 우승자를 결정해야합니다. 이동하시겠습니까?";
		} else {
			title = "우승자 결정완료!";
			msg = "참여 한 토너먼트의 우승자 결정이 완료되었습니다. 결과를 보기위해 이동하시겠습니까?";
		}
		new AlertDialog.Builder(this)
		.setTitle(title)
		.setMessage(msg)
		.setPositiveButton("이동", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				if (isNetworkAvailableAndNotice()) {
					dialog.dismiss();
					int gotoTournamentID = 0;
					if (not_select_winner_tournamentID != 0) {
						gotoTournamentID = not_select_winner_tournamentID;
					} else {
						gotoTournamentID = not_view_winner_tournamentID;
					}
					Intent intent = new Intent(JoinedTournamentListActivity.this, InfoTournamentActivity.class);
					intent.putExtra("tournamentID", "" + gotoTournamentID);
					startActivity(intent);
					
				}
			}
		})
		.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		}).show();
		
	}
}
